/**
 * 通知红点管理器
 */
class NotificationManager {
    constructor() {
        this.init();
    }

    init() {
        // 页面加载完成后加载通知数量
        this.loadNotifications();
        
        // 设置定期刷新通知数量（每30秒）
        setInterval(() => {
            this.loadNotifications();
        }, 30000);
    }

    /**
     * 加载通知数量
     */
    async loadNotifications() {
        try {
            console.log('开始加载通知数量...');
            const response = await fetch('/xuanzheng-company/pendingNotifications');
            console.log('响应状态:', response.status);
            
            if (response.ok) {
                const data = await response.json();
                console.log('接收到的通知数据:', data);
                if (data.success) {
                    this.updateNotificationUI(data.notifications);
                } else {
                    console.error('服务器返回错误:', data.message);
                }
            } else {
                console.error('请求失败，状态码:', response.status);
                const errorText = await response.text();
                console.error('错误响应:', errorText);
            }
        } catch (error) {
            console.error('加载通知数量失败:', error);
        }
    }

    /**
     * 更新通知UI显示
     */
    updateNotificationUI(notifications) {
        console.log('开始更新通知UI，数据:', notifications);
        
        // 清除所有现有的通知标记
        this.clearAllNotifications();

        // 根据通知数据更新红点显示
        for (const [menuItem, count] of Object.entries(notifications)) {
            console.log(`更新菜单项 ${menuItem} 的通知数量: ${count}`);
            this.showNotification(menuItem, count);
        }
    }

    /**
     * 显示特定菜单项的通知红点
     */
    showNotification(menuItem, count) {
        const notificationElement = document.getElementById(`notification-${menuItem}`);
        console.log(`寻找元素: notification-${menuItem}, 找到:`, notificationElement);
        
        if (notificationElement) {
            if (count > 0) {
                const displayCount = count > 99 ? '99+' : count.toString();
                console.log(`设置通知显示: ${menuItem} = ${displayCount}`);
                notificationElement.textContent = displayCount;
                notificationElement.classList.add('show');
                console.log('元素类名:', notificationElement.classList.toString());
            } else {
                notificationElement.classList.remove('show');
            }
        } else {
            console.warn(`未找到通知元素: notification-${menuItem}`);
        }
    }

    /**
     * 隐藏特定菜单项的通知红点
     */
    hideNotification(menuItem) {
        const notificationElement = document.getElementById(`notification-${menuItem}`);
        if (notificationElement) {
            notificationElement.classList.remove('show');
        }
    }

    /**
     * 清除所有通知红点
     */
    clearAllNotifications() {
        const allNotifications = document.querySelectorAll('.notification-count, .notification-badge');
        allNotifications.forEach(element => {
            element.classList.remove('show');
        });
    }

    /**
     * 手动刷新通知数量（用于用户操作后立即更新）
     */
    refreshNotifications() {
        this.loadNotifications();
    }

    /**
     * 标记特定类型的通知为已处理（减少计数）
     */
    async markAsProcessed(menuItem, count = 1) {
        // 先立即隐藏或减少计数，然后刷新
        const notificationElement = document.getElementById(`notification-${menuItem}`);
        if (notificationElement) {
            const currentCount = parseInt(notificationElement.textContent) || 0;
            const newCount = Math.max(0, currentCount - count);
            
            if (newCount === 0) {
                notificationElement.classList.remove('show');
            } else {
                notificationElement.textContent = newCount > 99 ? '99+' : newCount.toString();
            }
        }

        // 延迟刷新以确保服务器数据已更新
        setTimeout(() => {
            this.loadNotifications();
        }, 1000);
    }
}

// 全局通知管理器实例
let notificationManager;

// 页面加载完成后初始化通知管理器
document.addEventListener('DOMContentLoaded', function() {
    notificationManager = new NotificationManager();
    
    // 将通知管理器暴露到全局作用域，便于其他脚本调用
    window.notificationManager = notificationManager;
    
    // 测试功能：显示所有可能的通知红点（用于调试）
    window.testNotifications = function() {
        console.log('测试通知红点显示...');
        
        // 查找所有通知元素
        const allNotificationElements = document.querySelectorAll('[id^="notification-"]');
        console.log('找到的通知元素:', allNotificationElements);
        
        allNotificationElements.forEach((element, index) => {
            element.textContent = (index + 1).toString();
            element.classList.add('show');
            console.log('测试显示元素:', element.id);
        });
    };
    
    // 清除测试通知
    window.clearTestNotifications = function() {
        const allNotificationElements = document.querySelectorAll('[id^="notification-"]');
        allNotificationElements.forEach(element => {
            element.classList.remove('show');
        });
    };
});

// 监听菜单点击事件，当用户点击含有通知的菜单项时，可以选择性地刷新通知
document.addEventListener('click', function(e) {
    const menuLink = e.target.closest('.submenu-item a');
    if (menuLink) {
        const target = menuLink.getAttribute('data-target');
        
        // 对于某些特定的菜单项，点击后刷新通知数量
        const refreshTargets = [
            'system-applications',
            'employee-applications', 
            'resignation-applications',
            'task-management'
        ];
        
        if (refreshTargets.includes(target)) {
            // 延迟刷新，给页面内容加载一些时间
            setTimeout(() => {
                if (window.notificationManager) {
                    window.notificationManager.refreshNotifications();
                }
            }, 500);
        }
    }
});